package demo.stream;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.client.deployment.executors.PipelineExecutorUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.PrintSinkFunction;
import org.apache.flink.streaming.api.functions.source.SocketTextStreamFunction;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.util.Collector;
import org.apache.flink.api.java.tuple.Tuple2;

public class WordCount {

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        SocketTextStreamFunction socketTextStreamFunction = new SocketTextStreamFunction("127.0.0.1", 8888, "\n", 1);
        DataStreamSource<String> ds = env.addSource(socketTextStreamFunction);

        SingleOutputStreamOperator<Tuple2<String, Long>> oper1 = ds.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                for (String s1 : s.split(",")) {
                    collector.collect(new Tuple2<String, Long>(s1, 1L));
                }
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Long>> sum = oper1.keyBy(v -> v.f0)
                .sum(1);

        sum.print();
//        sum.addSink(new PrintSinkFunction<>());

        StreamGraph streamGraph = env.getStreamGraph();
        System.out.println(streamGraph);

        JobGraph jobGraph = PipelineExecutorUtils.getJobGraph(streamGraph, new Configuration());



        env.execute("app");
    }
}
